import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    isLoggedIn: localStorage.getItem('userLoggedIn') === 'true',
    role: localStorage.getItem('userRole') || '',
    userType: parseInt(localStorage.getItem('userType') || '0'),
    username: localStorage.getItem('userName') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  }),
  getters: {
    isUser() {
      return this.role === 'user' || this.userType === 1
    },
    isStatistician() {
      return this.role === 'statistician' || this.userType === 2
    },
    isAdmin() {
      return this.role === 'admin' || this.userType === 3
    }
  },
  actions: {
    login(userData) {
      this.isLoggedIn = true
      this.role = userData.role
      this.userType = userData.userType || 0
      this.username = userData.username
      this.userInfo = userData
      
      // 持久化存储到localStorage
      localStorage.setItem('userLoggedIn', 'true')
      localStorage.setItem('userRole', userData.role)
      localStorage.setItem('userType', userData.userType || 0)
      localStorage.setItem('userName', userData.username)
      localStorage.setItem('userInfo', JSON.stringify(userData))
    },
    logout() {
      this.isLoggedIn = false
      this.role = ''
      this.userType = 0
      this.username = ''
      this.userInfo = {}
      
      // 清除localStorage中的用户信息
      localStorage.removeItem('userLoggedIn')
      localStorage.removeItem('userRole')
      localStorage.removeItem('userType')
      localStorage.removeItem('userName')
      localStorage.removeItem('userInfo')
      
      // 重定向到登录页面
      window.location.href = '/login'
    },
    updateUserInfo(info) {
      this.userInfo = { ...this.userInfo, ...info }
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    }
  }
})